<template>
    <el-header>
        <h2>采购订单记录</h2>
        <div style="float: left; margin-bottom: 16px;">
            <el-form :model="form" label-width="auto" style="display: flex; gap: 24px; flex-wrap: wrap;">
                <el-input v-model="form.procurementOrder_code" style="width: 200px; height: 2rem;"
                    placeholder="请输入订单编号或者供应商" />
                <el-form-item label="日期：" prop="valid_period">
                    <el-date-picker v-model="tempDateRange" type="datetimerange" range-separator="~"
                        start-placeholder="开始日期" end-placeholder="结束日期" style="width: 400px;"
                        @change="handleDateRangeChange" />
                </el-form-item>
                <!-- 商品 -->
                <el-form-item label="商品：">
                    <el-input v-model="goodsInput" readonly placeholder="选择商品" @click="openGoodsDialog"
                        style="width: 150px" />
                </el-form-item>

                <el-form-item label="订单状态：">
                    <el-select v-model="form.procurementOrder_status" placeholder="请选择状态" clearable
                        style="width: 120px;">
                        <el-option label="待审核" value="2" />
                        <el-option label="已审核" value="3" />
                        <el-option label="已保存" value="1" />
                        <el-option label="已驳回" value="4" />
                    </el-select>
                </el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form>
        </div>
        <div style="float: left;">
            展示详情：<el-switch v-model="showDetails" @change="changeShow" />
        </div>
        <div style="gap: 12px; float: right; margin-bottom: 16px;">
            <el-button type="primary" @click="addComparison">新增</el-button>
            <el-button @click="batchCheck" :disabled="selectedRows.length === 0">审核</el-button>
            <el-button>反审核</el-button>
            <el-button @click="batchSubmit" :disabled="selectedRows.length === 0">提交</el-button>
            <el-button @click="handleImport">导入</el-button>
            <el-button @click="write" :disabled="selectedRows.length === 0">导出</el-button>
        </div>

        <!-- 导入对话框 -->
        <el-dialog v-model="importDialogVisible" title="导入采购订单" width="500px">
            <div class="import-dialog-content">
                <el-upload ref="uploadRef" class="upload-demo" action="" :auto-upload="false" :file-list="fileList"
                    :on-change="handleFileChange" :on-remove="handleFileRemove" accept=".xlsx" drag>
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">
                        将文件拖到此处，或<em>点击上传</em>
                    </div>
                    <template #tip>
                        <div class="el-upload__tip">
                            <div>请上传.xlsx格式的Excel文件</div>
                            <div>文件大小不超过10MB</div>
                            <div>请确保文件格式正确</div>
                        </div>
                        <!-- 下载模板链接 -->
                        <div style="margin-top: 10px;">
                            <a href="/lxw/writeProcurementOrder?procurementOrder_id=1476806e-999c-41e3-9c2d-99b50f82d1bf,8b582334-c9e6-46e8-b99a-cc27a94a742a"
                                style="color: #409eff; text-decoration: none;">
                                 <el-icon><Download /></el-icon>
                                下载导入模板
                            </a>
                        </div>
                    </template>
                </el-upload>

                <div v-if="importResult" class="import-result" :class="importResult.type">
                    <el-icon>
                        <CircleCheck v-if="importResult.type === 'success'" />
                        <CircleClose v-else />
                    </el-icon>
                    <span>{{ importResult.message }}</span>
                </div>
            </div>

            <template #footer>
                <el-button @click="importDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitImport" :disabled="!fileList.length" :loading="importLoading">
                    开始导入
                </el-button>
            </template>
        </el-dialog>

        <div class="table-wrapper">
            <el-table :data="filteredInquiryList" style="width: 100%" :row-class-name="tableRowClassName" height="100%"
                @row-click="handleRowClick" @selection-change="handleSelectionChange" ref="tableRef">
                <el-table-column type="selection" width="55px">
                </el-table-column>
                <!-- <el-table-column label="序号" type="index" width="100" /> -->
                <el-table-column prop="procurementOrder_date" label="订单日期" width="180" />
                <el-table-column prop="procurementOrder_code" label="采购订单编号" width="180" />
                <el-table-column prop="supplier_name" label="供应商" width="180" />
                <el-table-column prop="created_by" label="业务员" width="180" />
                <el-table-column prop="procurement_code" label="关联购货单号" width="180" />
                <el-table-column prop="salesSlip_code" label="关联销货单号" width="180" />
                <el-table-column prop="procurement_amount" label="购买金额" width="180" />
                <el-table-column prop="discount_amount" label="优惠金额" width="180" />
                <el-table-column prop="afterDiscount_amount" label="优惠后金额" width="180" />
                <el-table-column prop="tax_amount" label="税额" width="180" />
                <el-table-column prop="procurementOrder_num" label="数量" width="180" />
                <el-table-column prop="procurementOrder_status" label="订单状态" width="180">
                    <template #default="scope">
                        <el-tag :type="getStatusTagType(scope.row.procurementOrder_status)">
                            {{ getInquiryStatus(scope.row.procurementOrder_status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="delivery_date" label="交货日期（整单）" width="180" />
                <!-- 明细 -->
                <el-table-column v-if="showDetails" prop="goods_name" label="商品" width="180" />
                <el-table-column v-if="showDetails" prop="goods_brand" label="品牌" width="180" />
                <el-table-column v-if="showDetails" prop="goods_specifiction" label="属性" width="180" />
                <el-table-column v-if="showDetails" prop="goods_remark" label="商品备注" width="180" />
                <el-table-column v-if="showDetails" prop="goods_moreUint" label="单位" width="180" />
                <el-table-column v-if="showDetails" prop="goods_store" label="仓库" width="180" />
                <el-table-column v-if="showDetails" prop="store_userNum" label="可用库存" width="180" />
                <el-table-column v-if="showDetails" prop="procureDetails_num" label="数量（明细）" width="180" />
                <el-table-column v-if="showDetails" prop="goods_unit" label="基本单位" width="180" />
                <el-table-column v-if="showDetails" prop="unit_num" label="基本数量" width="180" />
                <el-table-column v-if="showDetails" prop="procurementDetails_Deliverydate" label="交货日期（明细）"
                    width="180" />
                <el-table-column v-if="showDetails" prop="goods_price" label="购货单价" width="180" />
                <el-table-column v-if="showDetails" prop="sale_price" label="销售价" width="180" />
                <el-table-column v-if="showDetails" prop="wholeSale_price" label="批发价" width="180" />
                <el-table-column v-if="showDetails" prop="gift" label="赠品" width="180">
                    <template #default="{ row }">
                        {{ row.gift == false ? '' : '是' }}
                    </template>
                </el-table-column>
                <el-table-column v-if="showDetails" prop="discount_price" label="折后单价" width="180" />
                <el-table-column v-if="showDetails" prop="afterDiscount_price" label="含税单价" width="180" />
                <el-table-column v-if="showDetails" prop="afterDiscount_taxPrice" label="折后含税单价" width="180" />
                <el-table-column v-if="showDetails" prop="discount" label="折扣率（%）" width="180" />
                <el-table-column v-if="showDetails" prop="discount_amount" label="折扣额" width="180" />
                <el-table-column v-if="showDetails" prop="amount" label="金额（明细）" width="180" />
                <el-table-column v-if="showDetails" prop="tax" label="税率（%）" width="180" />
                <el-table-column v-if="showDetails" prop="tax_amount" label="税额" width="180" />
                <el-table-column v-if="showDetails" prop="totalAmount_includingTax" label="价税合计" width="180" />
                <el-table-column v-if="showDetails" prop="procurementDetails_salesOrder_code" label="关联销售订单"
                    width="180" />
                <el-table-column v-if="showDetails" prop="outstanding_quantity" label="未入库数量" width="180" />
                <!-- 明细 -->
                <el-table-column prop="created_by" label="制单人" width="180" />
                <el-table-column prop="created_date" label="制单时间" width="180" />
                <el-table-column prop="checked_by" label="数量" width="180" />
                <el-table-column prop="procurementOrder_remark" label="备注" width="180" />
                <el-table-column prop="delivery_method" label="交货方式" width="180" />
                <el-table-column prop="printf_num" label="打印次数" width="180" />
                <el-table-column prop="name" label="操作" width="220" fixed="right">
                    <template #default="scope">
                        <el-button size="small" type="warning" @click="deleteOrder(scope.row)">
                            删除
                        </el-button>
                        <el-button size="small"
                            v-show="scope.row.procurementOrder_status !== 2 && scope.row.procurementOrder_status !== 3"
                            type="primary" @click="modifyOrder(scope.row)">
                            修改
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-pagination style="float: right; margin-top: 16px;" background layout="prev, pager, next,jumper"
            :total="pageInfo.total" :page-size="pageInfo.pageSize" :current-page="pageInfo.pageNum"
            @current-change="changePage" v-model:current-page="pageInfo.pageNum" />


    </el-header>
    <!-- 调用商品选择组件 -->
    <!-- <GoodsSelectDialog v-model:visible="goodsDialogVisible" :data-source="productDataSource"
        :selected="selectedProducts" @confirm="handleGoodsConfirm" @cancel="handleGoodsCancel" /> -->

    <!-- 商品搜索列表弹出对话框 -->
    <el-dialog v-model="goodsDialogVisible" title="商品搜索列表" width="40%" style="height: auto; width: 800px;" draggable
        :show-close="true">
        <!-- 调用商品的搜索组件 -->
        <FreeGoodsSelect v-model="goodsDialogVisible" :selected="selectedProducts" @confirm="handleGoodsConfirm">
        </FreeGoodsSelect>
        <br /><br />
    </el-dialog>
</template>

<script setup>
import { reactive, ref, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
// import GoodsSelectDialog from '@/util/GoodsSelectDialog.vue';
import FreeGoodsSelect from "@/util/FreeGoodsSelect.vue";
import axios from 'axios';
const showDetails = ref(true)

const router = useRouter();

// 添加导入相关响应式数据
const importDialogVisible = ref(false)
const importLoading = ref(false)
const uploadRef = ref()
const fileList = ref([])
const importResult = ref(null)

// 导入方法
const handleImport = () => {
    importDialogVisible.value = true
    // 重置状态
    fileList.value = []
    importResult.value = null
}

// 文件选择变化
const handleFileChange = (file, files) => {
    // 只允许上传一个文件
    if (files.length > 1) {
        fileList.value = files.slice(-1)
    } else {
        fileList.value = files
    }

    // 验证文件类型
    const isXLSX = file.name.toLowerCase().endsWith('.xlsx')
    if (!isXLSX) {
        ElMessage.error('只能上传.xlsx格式的Excel文件')
        fileList.value = []
        return false
    }

    // 验证文件大小（10MB）
    const isLt10M = file.size / 1024 / 1024 < 10
    if (!isLt10M) {
        ElMessage.error('文件大小不能超过10MB')
        fileList.value = []
        return false
    }

    importResult.value = null
    return true
}

// 文件移除
const handleFileRemove = () => {
    fileList.value = []
    importResult.value = null
}

// 提交导入
const submitImport = async () => {
    if (fileList.value.length === 0) {
        ElMessage.warning('请选择要导入的文件')
        return
    }

    const file = fileList.value[0].raw
    if (!file) {
        ElMessage.error('文件不存在')
        return
    }

    try {
        importLoading.value = true
        importResult.value = null

        // 创建FormData
        const formData = new FormData()
        formData.append('file', file)

        // 发送请求到你的后端接口
        const response = await axios.post('/lxw/uploadProcurementOrder', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            timeout: 60000 // 60秒超时
        })

        console.log('导入响应:', response.data)

        if (response.data.code === '5200' || response.data.code === 5200) {
            importResult.value = {
                type: 'success',
                message: response.data.msg || '导入成功'
            }
            ElMessage.success('导入成功')

            // 导入成功后刷新数据
            setTimeout(() => {
                importDialogVisible.value = false
                // 重新加载数据
                if (showDetails.value) {
                    getOrderPageInfo()
                } else {
                    getOrderMainPageInfo()
                }
            }, 1500)
        } else {
            importResult.value = {
                type: 'error',
                message: response.data.msg || '导入失败'
            }
            ElMessage.error(response.data.msg || '导入失败')
        }
    } catch (error) {
        console.error('导入失败:', error)
        let errorMessage = '导入失败'

        if (error.response) {
            // 处理后端返回的错误信息
            if (error.response.data && error.response.data.msg) {
                errorMessage = error.response.data.msg
            } else {
                errorMessage = '服务器错误，请稍后重试'
            }
        } else if (error.request) {
            errorMessage = '网络错误，请检查网络连接'
        } else {
            errorMessage = error.message
        }

        importResult.value = {
            type: 'error',
            message: errorMessage
        }
        ElMessage.error(errorMessage)
    } finally {
        importLoading.value = false
    }
}

const form = reactive({
    procurementOrder_id: '',
    procurementOrder_code: '',
    procurementOrder_status: '',
    goods_store: '',
    goods_name: '',
    start_Date: '',
    end_Date: ''
})
const pageInfo = reactive({
    total: 0,
    pageSize: 8,
    pageNum: 1
});

const initPageInfo = () => {
    pageInfo.pageNum = 1
    pageInfo.pageSize = 8
    pageInfo.total = 0
}
const orderPageInfo = ref([])
// 新增：选中的行数据和表格引用
const selectedRows = ref([])
const tableRef = ref()
const auditLoading = ref(false)
const loading = ref(false)

onMounted(() => {
    getOrderPageInfo()
})

const onSubmit = () => {
    console.log('查询参数：', form);
    if (showDetails.value) {
        getOrderPageInfo()
    }
    else {
        getOrderMainPageInfo()
    }

};

//是否展示详情
const changeShow = async () => {
    if (showDetails.value) {
        getOrderPageInfo()
    } else {
        initPageInfo()
        getOrderMainPageInfo()
    }
}
//获取记录明细
const getOrderPageInfo = async () => {
    const params = {
        pageNum: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
        procurementOrder_code: form.procurementOrder_code,
        procurementOrder_status: form.procurementOrder_status,
        goods_store: form.goods_store,
        goods_name: form.goods_name,
        start_Date: formatDate(form.start_Date) == '' ? null : formatDate(form.start_Date),
        end_Date: formatDate(form.end_Date) == '' ? null : formatDate(form.end_Date)
    }
    loading.value = true
    const res = await axios.get('/lxw/orderPageInfo', { params })
    console.log(res)
    if (res.data.code == 5200) {
        orderPageInfo.value = res.data.orderPageInfo
        pageInfo.pageNum = res.data.orderPageInfo.pageNum
        pageInfo.pageSize = res.data.orderPageInfo.pageSize
        pageInfo.total = res.data.orderPageInfo.total
    }
    else {
        ElMessage.error(res.data.msg)
    }
}
//
const getOrderMainPageInfo = async () => {
    const params = {
        pageNum: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
        companyCode: 'CNY001',
        procurementOrder_code: form.procurementOrder_code,
        procurementOrder_status: form.procurementOrder_status,
        goods_store: form.goods_store,
        goods_name: form.goods_name,
        order_startDate: formatDate(form.start_Date) == '' ? null : formatDate(form.start_Date),
        order_endDate: formatDate(form.end_Date) == '' ? null : formatDate(form.end_Date)
    }
    const res = await axios.get('/lxw/selectAllOrder', { params })
    console.log(res)
    if (res.data.code == 5200) {
        orderPageInfo.value = res.data.orderPageInfo
        pageInfo.pageNum = res.data.orderPageInfo.pageNum
        pageInfo.pageSize = res.data.orderPageInfo.pageSize
        pageInfo.total = res.data.orderPageInfo.total
    }
}
// 选择框变化事件
const handleSelectionChange = (selection) => {
    selectedRows.value = selection
    //把选择的采购订单id使用,隔开
    const orderIds = [...new Set(selectedRows.value.map(item => item.procurementOrder_id))]

    updateSourceOrderCodes(orderIds)
    console.log('选中的行:', selectedRows.value)
}
// 批量审核
const batchCheck = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要审核的采购订单')
        return
    }

    // 验证选中的单据状态
    const invalidRows = selectedRows.value.filter(row =>
        row.procurementOrder_status != '2'
    )

    if (invalidRows.length > 0) {
        const invalidCodes = invalidRows.map(row => row.procurementOrder_code).join(', ')
        ElMessage.warning(`以下单据状态不符合审核要求: ${invalidCodes}`)
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要对选中的 ${selectedRows.value.length} 个采购订单进行审核吗？`,
            '批量审核确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        auditLoading.value = true

        // 批量审核
        const results = await Promise.allSettled(
            selectedRows.value.map(row =>
                axios.post(`/lxw/checkProcurementOrder?procurementOrder_id=${row.procurementOrder_id}`)
            )
        )

        const successCount = results.filter(result =>
            result.status === 'fulfilled' && result.value.data.code === '5200'
        ).length

        const failCount = results.length - successCount

        if (successCount > 0) {
            ElMessage.success(`成功审核 ${successCount} 个采购订单`)
        }
        if (failCount > 0) {
            ElMessage.warning(`${failCount} 个采购订单审核失败`)
        }

        // 重新加载数据
        if (showDetails.value) {
            getOrderPageInfo()
        }
        else {
            getOrderMainPageInfo()
        }
        // 清空选择
        clearSelection()

    } catch (error) {
        console.log('用户取消操作')
    } finally {
        auditLoading.value = false
    }
}

// 批量提交
const batchSubmit = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要提交的采购订单')
        return
    }

    // 验证选中的单据状态
    const invalidRows = selectedRows.value.filter(row =>
        row.procurementOrder_status != '1'
    )

    if (invalidRows.length > 0) {
        const invalidCodes = invalidRows.map(row => row.procurementOrder_code).join(', ')
        ElMessage.warning(`以下单据状态不符合审核要求: ${invalidCodes}`)
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要对选中的 ${selectedRows.value.length} 个采购订单进行提交吗？`,
            '批量提交确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        auditLoading.value = true

        // 批量提交
        const results = await Promise.allSettled(
            selectedRows.value.map(row =>
                axios.post(`/lxw/submitProcurementOrder?procurementOrder_id=${row.procurementOrder_id}`)
            )
        )

        const successCount = results.filter(result =>
            result.status === 'fulfilled' && result.value.data.code === '5200'
        ).length

        const failCount = results.length - successCount

        if (successCount > 0) {
            ElMessage.success(`成功提交 ${successCount} 个采购订单`)
        }
        if (failCount > 0) {
            ElMessage.warning(`${failCount} 个采购订单提交失败`)
        }

        // 重新加载数据
        if (showDetails.value) {
            getOrderPageInfo()
        }
        else {
            getOrderMainPageInfo()
        }
        // 清空选择
        clearSelection()

    } catch (error) {
        console.log('用户取消操作')
    } finally {
        auditLoading.value = false
    }
}

// 批量导出
const write = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要导出的采购订单')
        return
    }
    try {
        await ElMessageBox.confirm(
            `确定要对选中的 ${selectedRows.value.length} 个采购订单进行导出吗？`,
            '批量提交确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        auditLoading.value = true
        // 批量提交
        // 使用 blob 方式下载文件
        const response = await axios({
            method: 'get',
            url: '/lxw/writeProcurementOrder',
            params: {
                procurementOrder_id: form.procurementOrder_id
            },
            responseType: 'blob' // 重要：指定响应类型为 blob
        })
        // 创建 blob 链接并下载
        const blob = new Blob([response.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })

        // 创建下载链接
        const downloadUrl = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = downloadUrl

        // 从响应头获取文件名，如果没有则使用默认名
        const fileName = getFileNameFromResponse(response) || `采购订单_${new Date().getTime()}.xlsx`
        link.download = fileName

        // 触发下载
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        // 释放 blob URL
        window.URL.revokeObjectURL(downloadUrl)

        ElMessage.success(`成功导出 ${selectedRows.value.length} 个采购订单`)

        // 清空选择
        clearSelection()
    } catch (error) {
        console.log('用户取消操作')
    } finally {
        auditLoading.value = false
    }
}

// 从响应头获取文件名
const getFileNameFromResponse = (response) => {
    const contentDisposition = response.headers['content-disposition']
    if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename\*?=utf-8''(.+)/i)
        if (fileNameMatch && fileNameMatch[1]) {
            return decodeURIComponent(fileNameMatch[1])
        }
    }
    return null
}
const updateSourceOrderCodes = (newOrderCodes) => {
    // 直接使用当前选中的所有订单ID，不保留之前的
    const filteredCodes = newOrderCodes.filter(code => code && code.trim() !== '');

    // 更新表单字段
    form.procurementOrder_id = filteredCodes.join(',');

    console.log('更新后的采购订单id:', form.procurementOrder_id);
}

//清空选择
const clearSelection = () => {
    if (tableRef.value) {
        tableRef.value.clearSelection()
    }
    selectedRows.value = []
}
// 行点击事件
const handleRowClick = (row) => {
    // 可以在这里处理点击逻辑
    console.log('点击:', row)
}


// 临时存储日期范围
const tempDateRange = ref([])

// 日期范围变化处理
const handleDateRangeChange = (dateRange) => {
    if (dateRange && dateRange.length === 2) {
        form.start_Date = dateRange[0]
        form.end_Date = dateRange[1]
    } else {
        form.start_Date = ''
        form.end_Date = ''
    }
}


// 控制弹窗显示
const goodsDialogVisible = ref(false)
// 已选商品
const selectedProducts = ref([])

// 打开商品选择弹窗
const openGoodsDialog = () => {
    goodsDialogVisible.value = true
}
const goodsInput = ref('')
// 确认选择商品
const handleGoodsConfirm = (selected) => {
    selectedProducts.value = selected
    // 将选中的商品名称显示在输入框中
    if (selected && selected.length > 0) {
        goodsInput.value = selected.map(item => item.name).join(',')
        form.goods_name = selected.map(item => item.name).join(',')
    } else {
        goodsInput.value = ''
        form.goods_name = ''
    }
    goodsDialogVisible.value = false
    console.log('选中的商品:', selected)
    console.log('选择的商品列表', goodsInput)
}
// 取消选择
// const handleGoodsCancel = () => {
//     // 处理取消逻辑
// }

const filteredInquiryList = computed(() => {
    return (orderPageInfo.value.list || [])
})


// 方法
const addComparison = () => {
    router.push({ name: 'addProcurementOrder' });
}

// 修改 modifyOrder 方法
const modifyOrder = async (row) => {
    try {
        // 先获取最新数据，避免数据过期
        const res = await axios.get(`/lxw/selectByOrderId?procurementOrder_id=${row.procurementOrder_id}`);
        if (res.data.code == 5200) {
            router.push({
                name: 'addProcurementOrder',
                query: {
                    isEdit: true,
                    procurementOrder_id: row.procurementOrder_id
                }
            });
        } else {
            ElMessage.error('获取数据失败');
        }
    } catch (error) {
        console.error('获取数据失败:', error);
        ElMessage.error('获取数据失败');
    }
}

// 添加删除方法
const deleteOrder = async (row) => {
    try {
        await ElMessageBox.confirm('确定要删除这个询价单吗？', '删除确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        if (row.procurementOrder_status == 3 || row.procurementOrder_status == 2) {
            ElMessage.error('该状态不可删除');
            return
        }
        const res = await axios.get(`/lxw/deleteProcurementOrder?procurementOrder_id=${row.procurementOrder_id}`);

        if (res.data.code == 5200) {
            ElMessage.success('删除成功');
            getOrderPageInfo(); // 重新加载数据
        } else {
            ElMessage.error(res.data.msg);
        }
    } catch (error) {
        console.log('用户取消删除');
    }
}


// 状态标签类型
const getStatusTagType = (status) => {
    const statusMap = {
        '3': 'success',
        '2': 'warning',
        '1': 'warning',
        '4': 'danger',
        '0': 'danger'
    }
    return statusMap[status] || 'info'
}
const getInquiryStatus = (status) => {
    const statusMap = {
        '1': '已保留',
        '2': '待审核',
        '3': '已审核',
        '4': '已驳回'
    }
    return statusMap[status] || ''
}

const changePage = (page) => {
    pageInfo.pageNum = page;
    if (showDetails.value) {
        getOrderPageInfo()
    }
    else {
        getOrderMainPageInfo()
    }
};

const tableRowClassName = ({ rowIndex }) => {
    return {
        'table-row-even': rowIndex % 2 === 0,
        'table-row-odd': rowIndex % 2 !== 0
    };
};

// 改进的日期格式化函数
// 日期格式化函数
// 方法二：使用 ISO 字符串转换
// 日期格式化
const formatDate = (date) => {
    if (!date) return '';
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};


</script>

<style scoped>
/*  */
.supplier-dialog {
    max-height: 70vh;
    overflow-y: auto;
}

.dialog-footer {
    text-align: center;
    margin-top: 16px;
}

/* 使输入框看起来可点击 */
:deep(.el-input.is-disabled .el-input__inner) {
    background-color: #f5f7fa;
    border-color: #e4e7ed;
    color: #606266;
    cursor: pointer;
}

:deep(.el-input.is-disabled .el-input__inner:hover) {
    border-color: #c0c4cc;
}

/*  */
.form-section {
    margin-bottom: 24px;
    padding: 16px;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
}

.fixed-height-dialog {
    max-height: 80vh;
}

:deep(.fixed-height-dialog .el-dialog__body) {
    max-height: 60vh;
    overflow-y: auto;
    padding: 20px;
}

.dialog-content {
    min-height: 400px;
}

.demo-tabs>.el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
}

/* 核心修改：表格容器样式 */
.table-wrapper {
    height: 400px;
    /* 固定高度，这是关键 */
    overflow: auto;
    border: 1px solid #e8e8e8;
    display: block;
    clear: both;
}

/* 确保表头固定 */
:deep(.el-table__header-wrapper) {
    position: sticky;
    top: 0;
    z-index: 10;
}

/* 可选：给表头添加背景色，避免透明 */
:deep(.el-table th) {
    background-color: #f5f7fa;
}

/* 隔行变色样式 */
:deep(.table-row-even) {
    background-color: #f9f9f9;
}

:deep(.table-row-odd) {
    background-color: #fff;
}

.product-details {
    padding: 20px;
    background: #f8f9fa;
}
</style>